package DataBaseConnection;
import java.sql.*;
/**
 * 
 * @author 吴林春
 *2018年10月29日
 *DataBaseConnection
 *CivilAviationTicketSystem
 */

/**@use数据库连接类
*
 */
public class DataBaseManager {
	private static String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
	private static String url = "jdbc:sqlserver://localhost:1433;databaseName = CivilAviationTicketSystem", user = "AAA", password = "123456";
	private static Connection conn = null;
	static {
		try {
			Class.forName(driver);   //加载SQLServerDriver类中的静态代码块
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	/* 执行select语句，返回唯一值 */
	public static Object executeSingleQuery(String singleSql) {
		Object r = null;
		ResultSet rs = null;
		try {
			Connection conn = DriverManager.getConnection(url, user, password);  //数据库连接
			Statement cmd = conn.createStatement();      //数据库操作,用于执行静态的SQL语句并返回它所生成结果的对象
			rs = cmd.executeQuery(singleSql);
			if (rs.next()) {
				r = rs.getObject(1);
			}
			conn.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return r;
	}

	public static void closeConnection() {
		try {
			if (conn != null && !conn.isClosed()) {
				conn.close();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/* 执行select语句 */
	public static ResultSet executeQuery(String sql) {
		ResultSet rs = null;
		try {
			conn = DriverManager.getConnection(url, user, password);
			Statement cmd = conn.createStatement();
			rs = cmd.executeQuery(sql);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return rs;
	}

	/* 执行cuid操作 */
	public static int executeUpdate(String sql) {   //添加，更新操作
		int r = 0;
		try {
			Connection conn = DriverManager.getConnection(url, user, password);
			Statement cmd = conn.createStatement();
			r = cmd.executeUpdate(sql);
			conn.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return r;
	}

}
